define([
    'clipboard',
    'angular-loading-bar',
    'js/components/dialog'
], function(Clipboard) {
    var utilFactory = angular.module('app.util', ['angular-loading-bar', 'app.dialog']);

    utilFactory.factory('_util', function(cfpLoadingBar, _dialog) {
        var clipboard = null;
        return {
            copy: function(text) {
                var button = $('#clipboard-copy');
                if (button.length == 0) {
                    button = $('<button id="clipboard-copy" class="hidden"></button>');
                    button.appendTo(document.body);
                    clipboard = new Clipboard('#clipboard-copy', {
                        text: function() {
                            return text;
                        }
                    });
                } else {
                    clipboard.text = function() {
                        return text;
                    };
                }
                button.click();
            },
            download: function(url, params) {
                var jqTargetId = 'jqFormIO-' + (new Date().getTime());
                var jqForm = $('<form style="display:none">').attr({
                    method: 'GET',
                    action: url,
                    target: jqTargetId
                }).appendTo(document.body);
                _.each(params, function(value, name) {
                    jqForm.append($('<input type="hidden">').attr('name', name).val(value));
                });
                var jqIframe = $('<iframe style="display:none">').attr({
                    name: jqTargetId
                }).on('load', function() {
                    var body = $(this).contents().find('body');
                    if (body && body.length > 0) {
                        if (/^404$/.test(body.text())) {
                            _dialog.alert('提示信息', '下载的文件不存在或已被删除！');
                        }
                    }
                }).appendTo(document.body);
                // submit form
                cfpLoadingBar.start();
                jqForm.submit();
                // remove form & iframe
                setTimeout(function() {
                    jqForm.remove();
                    jqIframe.remove();
                    cfpLoadingBar.complete();
                }, 5000);
            }
        };
    });
});
